package edu.xmut.yuepai.common.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {


    // 默认有效期为 24 个小时
    public static final Long JWT_TTL = 24 * 60 * 60 * 1000L;
    // 签发的秘钥
    public static final String JWT_KEY = "shuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofengshuofeng";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    /**
     * 生成jtw
     *
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }


    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SecretKey secretKey = generalKey();
        // 获取当前时间的date对象
        Date now = new Date(System.currentTimeMillis());
        // 如果没有指定有效期，则使用默认
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        // 过期时间的date对象
        Date expDate = new Date(System.currentTimeMillis() + ttlMillis);
        return Jwts.builder()
                // 主题，可以是JSON数据
                .subject(subject)
                // 签发者
                .issuer("hwj")
                // 签发时间
                .issuedAt(now)
                .signWith(secretKey)
                // 过期时间
                .expiration(expDate);
    }


    public static void main(String[] args) throws Exception {
        // String jwt = createJWT("123");
        // System.out.println(jwt);
        Claims claims = parseJWT("123aCCg5Ww");
        String subject = claims.getSubject();
        System.out.println(subject);
    }

    /**
     * 生成加密后的秘钥 secretKey
     */
    public static SecretKey generalKey() {
        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(JWT_KEY));
    }

    /**
     * 解析
     *
     * @param jwt
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(jwt)
                .getPayload();

    }


}
